﻿using Serilog.Formatting.Compact;

namespace In66.Net.Share.Registrar.WebRegistrar
{
    public static partial class ServiceRegistrar
    {
        public static IServiceCollection AddLog(this IServiceCollection Services)
        {
            string template = "{Timestamp:HH:mm} || {Level} || {SourceContext:l} || {Message} || {Exception} ||end {NewLine}";

            Services.AddLogging(opt =>
            {
                Log.Logger = new LoggerConfiguration()
                .MinimumLevel.Information()
                .MinimumLevel.Override("Microsoft", LogEventLevel.Information)

                .Filter.ByExcluding(
                    e => e.Properties.TryGetValue("RequestPath", out var value)
                    && (value.ToString().Contains("LogDashboard")
                    //|| value.ToString().Contains("HealthCheck")
                    || value.ToString().Contains("_framework")
                    || value.ToString().Contains("swagger")
                    ))
                .Enrich.FromLogContext()

#if DEBUG
                .WriteTo.Console()//console
#else
                .WriteTo.Console(new RenderedCompactJsonFormatter())//stdout
                //.WriteTo.Console(new ElasticsearchJsonFormatter())//es
#endif
                .WriteTo.Logger(opt =>
                {
                    opt.WriteTo.Async(opt =>
                    {
                        opt.File(
                            $"{AppContext.BaseDirectory}log/Application/.log",
                            LogEventLevel.Information,
                            fileSizeLimitBytes: 10485760L,
                            retainedFileCountLimit: 31,
                            outputTemplate: template,
                            formatProvider: null,
                            levelSwitch: null,
                            buffered: false,
                            shared: true,
                            flushToDiskInterval: null,
                            rollingInterval: RollingInterval.Day,
                            rollOnFileSizeLimit: true
                            );
                    });
                }).CreateLogger();
            });
            return Services;
        }
    }
}
